/**
 * Created by liuqingxia on 2016/3/22.
 */

var params = {
    pageSize: 10
};

var currentAppId;

/*分表配置列表*/
var appTable;//无参数
var appTableWithParams;//有参数
var TBRuleTable;
var lookRule;//分表

/**
 * main入口
 */
$(document).ready(function () {

    LTS.colFormatter.optFormat = function (v, row) {
    	if(v==1){
    		return generateOptRule(row);
    	}
    	if(v == 0){
    		return generateOptNewRule(row);
    	}
    }
    LTS.colFormatter.tableOptFormat = function (v, row) {
    	return generateOptButtons(row);
    }
    LTS.colFormatter.groupOptFormat = function (v, row) {
    	return generateGroupOptButtons(row);
    }
    
    LTS.colFormatter.emptyString = function (v, row) {
        return emptyString(v);
    }

    LTS.colFormatter.sourceState = function (v, row) {
        return sourceState(row);
    }

    appTable = $("#tddlApp-table-container").ltsTable({
        url: getUrlBySuffix("/tddl/app/find"),
        templateId: 'tddlApp-table-template'
    });

    appTable.post(params, 1);

    appTableWithParams = $("#tddlApp-table-container").ltsTable({
        url: getUrlBySuffix("/tddl/app/findByAppName"),
        templateId: 'tddlApp-table-template'
    });

    TBRuleTable = $("#tddlAppRule-table-container").ltsTable({
        url: getUrlBySuffix("/tddl/appRule/findByAppId"),
        templateId: 'tddlAppRule-table-template'
    });
    
    lookRule = $("#appRuleContent-table-container").ltsTable({
    	url:getUrlBySuffix("/tddl/app/findAllAppTableByAppId"),
    	templateId : 'appRuleTable-table-template'
    });
    
    clickSearchBtn();
    clickTableRuleBtn();
    clickDBRuleBtn();
    clickSwitchBackupBtn();
    clickConfirmSwitchBackupBtn();
    clickDBSetBtn();
    /*app添加页*/
    clickAppInsertBtn();
    submitAppConfig();
    isDisabled();
    clickReloadSearchBtn();
    clickLookRuleBtn();
    clickValidateRuleBtn();
});

/**
 * 数据源状态
 * @param row
 * @returns {*}
 */
function sourceState(row) {
    var status = row['sourceState'];
    if (isNull(status)) {
        return "";
    }

    if (status == "可用") {
        return "<span style='color: green'>可用</span>";
    } else if (status == "不可用") {
        return "<span style='color: red'>不可用</span>";
    }
}

/**
 * 点击新建分表配置按钮
 */
function clickAppInsertBtn() {
    $(document).on("click", "#insertBtn", function () {
        window.location.href = getUrlBySuffix("/tddl/app/insert");
    });
}
/**
 * 验证规则
 * */
function clickValidateRuleBtn(){
	$(document).on("click","#validateRuleBtn",function(){
		$("#validateRuleGenerator-modal").modal("show");
	});
}

/**
 * 生成按钮
 * */
function generateOptRule(jsonObj){
	var optButtons = "" + setBtn +
	'<a href="javascript:;" class="DBRuleSearch-btn">' +
    '<span class="label label-success" style="font-size: 14px">' +
    '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
    '分组规则' +
    '</span>' +
    '</a>&nbsp;'+
    '<a href="javascript:;" class="RuleSearch-btn">' +
    '<span class="label label-success" style="font-size: 14px">' +
    '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
    '查看分表' +
    '</span>' +
    '</a>&nbsp;';

	return optButtons;
}
/**
 * 生成按钮
 * */
function generateOptNewRule(jsonObj){
	var optButtons = "" + setBtn +
	'<a href="javascript:;" class="DBRuleSearch-btn">' +
    '<span class="label label-success" style="font-size: 14px">' +
    '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
    '分组规则' +
    '</span>' +
    '</a>&nbsp;'+
    '<a href="javascript:;" class="RuleSearch-btn">' +
    '<span class="label label-success" style="font-size: 14px">' +
    '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
    '查看分表' +
    '</span>' +
    '</a>&nbsp;'+
    '<a href="javascript:;" class="reloadSearch-btn">' +
    '<span class="label label-success" style="font-size: 14px">' +
    '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
    '重新加载' +
    '</span>' +
    '</a>&nbsp;';

	return optButtons;
}
/**
 * 生成分表规则按钮
 * @param jsonObj
 * @returns {string}
 */
function generateOptButtons(jsonObj) {
    var optButtons = ""+
        '<a href="javascript:;" class="tableRuleSearch-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
        '分表规则' +
        '</span>' +
        '</a>&nbsp;';

    return optButtons;

}


/**
 * 生成操作按钮
 * @param jsonObj
 * @returns {string}
 */
function generateOptReloadButtons(jsonObj) {
    var optButtons = "" + setBtn +
        '<a href="javascript:;" class="DBRuleSearch-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
        '分组规则' +
        '</span>' +
        '</a>&nbsp;' +
        '<a href="javascript:;" class="tableRuleSearch-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
        '分表规则' +
        '</span>' +
        '</a>&nbsp;'+
        '<a href="javascript:;" class="reloadSearch-btn">' +
        '<span class="label label-success" style="font-size: 14px">' +
        '<i class="fa fa-search"></i>&nbsp;&nbsp;' +
        '重新加载' +
        '</span>' +
        '</a>&nbsp;';

    return optButtons;

}

/**
 * 根据id获取AppDataSource
 * @param id
 * @returns {*}
 */
function getAppDataSource(id) {
    var dataSource;
    $.postHttpSync({id: id}, getUrlBySuffix("/tddl/appDataSource/findById"), function (json) {
        if (json && json.success) {
            var list = json['list'];
            dataSource = list[0];
        }
    })
    return dataSource;
}

/**
 * 点击"搜索"按钮事件
 */
function clickSearchBtn() {
    $(document).on("click", "#searchBtn", function () {
        var appName = $.trim($("#logicTableName").val());
        if (isNull(appName)) {
            appTable.post({}, 1);
        } else {
            appTableWithParams.post({appName: appName}, 1);
        }
    });
}

/**
 * 点击"分表规则"按钮
 */
function clickTableRuleBtn() {
    $(document).on("click", ".tableRuleSearch-btn", function () {
        var appId = getCurrentId($(this));
        TBRuleTable.post({appId: appId}, 1);
        changeRuleTitleSpan("分表规则");
        $("#group_table_rule").show();
    });
}

/**
 *点击"分组规则"按钮事件
 */
function clickDBRuleBtn() {
    $(document).on("click", ".DBRuleSearch-btn", function () {
    	$("#appRuleIsShow").hide();
        var appId = getCurrentId($(this));
        currentAppId = appId;
        showDBRuleTable("tddlAppRule-table-container", appId);
        changeRuleTitleSpan("分组规则");
        $("#group_table_rule").show();
    });
}
/**
 * 点击‘重新加载’按钮
 * */
function clickReloadSearchBtn(){
	$(document).on("click",".reloadSearch-btn",function(){
		var appId = getCurrentId($(this));
		var appName = getCurrentAppName($(this));
		var url = getRoot() + "/tddl/app/reloadGddlShardApp";
		$("#appLoadingGenerator").modal("show");
		$.post(url,{"appId":appId,"appName":appName},function(data){
			if(data == "success"){
				$("#appLoadingGenerator").modal("hide");
				swal("成功","加载成功","success");
				window.setTimeout(function(){window.location.reload();},1000);
			}
			if(data == "error"){
				swal("失败","请重新加载","error");
			}
			
		});
	});
}
/**
 * 点击设置
 * */
function clickDBSetBtn(){
	$(document).on("click",".set-btn",function(){
		 var appId = getCurrentId($(this));
		 currentAppId = appId;
		 var url = getRoot() + "/tddl/app/findAppConfigById";
		 $.post(url,{"appId":appId},function(data){
			if (data != null) {
				$("#delayTime").removeAttr("disabled");
				$("#isSwitchAuto").val(data.isAutoSwitch);
				$("#delayTime").val(data.switchDelayTime);
				if(data.isAutoSwitch == 0){
					$("#delayTime").val("");
					$("#delayTime").attr("disabled","false");
				}
			}
			if(data == null || data == '' || data == 'undefined'){
				$("#isSwitchAuto").val(0);
				$("#delayTime").val("");
				$("#delayTime").attr("disabled","false");
			} 
		 });
		 $("#appConfigGenerator-modal").modal("show");
	});
}
/**
 * 点击查看分表按钮
 * */
function clickLookRuleBtn(){
	$(document).on("click",".RuleSearch-btn",function(){
		$("#appRuleContent-table-container").empty();
		var appId = getCurrentId($(this));
		lookRule.post({appId:appId},1);
		$("#group_table_rule").hide();
		$("#tddlAppRule-table-container").empty();
		$("#appRuleIsShow").show();
	});
}
/**
 * 点击设置 确定按钮
 * */
function submitAppConfig(){
	$("#commit-appcontrim-btn").click(function(){
		var appsId = currentAppId;
		var isSwitch = $("#isSwitchAuto").val();
		var delayTime = $("#delayTime").val();
		var url = getRoot() + "/tddl/app/saveAppConfig";
		$.post(url,{"appId":appsId,"isSwitch":isSwitch,"delayTime":delayTime},function(data){
			if(data == 'success'){
				$("#appConfigGenerator-modal").modal("hide");
				swal("success","修改成功","success");
			}else{
				swal("error","修改失败","error");
			}
		});
	});
}
function isDisabled(){
	$("#selectID").click(function(){
		var isSwitch = $("#isSwitchAuto").val();
		if(isSwitch == 1){
			$("#delayTime").removeAttr("disabled");
		}
		if(isSwitch == 0){
			$("#delayTime").val("");
			$("#delayTime").attr("disabled","false");
		}
	});
}
/**
 * "分表规则"/"分组规则"标题切换
 * @param title
 */
function changeRuleTitleSpan(title) {
    var titleSpan = $("#ruleTitle-span");
    titleSpan.empty();
    titleSpan.append($.trim(title));
}

/**
 * 展示分库规则表格
 * @param containerId
 * @param appId
 */
function showDBRuleTable(containerId, appId) {
    var groupRuleVOs = getGroupRuleVOByAppId(appId);
    var splitGroupRuleVOs = getSplitGroupRuleVOs(groupRuleVOs);
    var container = $("#" + containerId);
    container.empty();
    container.append(generateGroupRuleVOTable(splitGroupRuleVOs));
}
